﻿using System.Collections;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// UI 面板（图片）带动多个对象平移移动控制器
/// 可点击按钮切换位置，支持上下左右方向移动，带动子物体一起平滑过渡。
/// </summary>
public enum Direction
{
    Left,   // 向左
    Right,  // 向右
    Up,     // 向上
    Down    // 向下
}

public class AllImagesMover : MonoBehaviour
{
    [Header("移动配置")]
    public Direction currentDirection;           // 移动方向（左/右/上/下）
    public RectTransform imageRect;              // 被移动的主图像（UI面板）
    public GameObject[] movingObjects;           // 需要一起移动的子物体
    public float moveDuration = 0.3f;            // 平滑移动时长
    public Button btn;                           // 点击触发移动的按钮

    // 运行时状态
    private Vector2 originalPos;                 // 主图片原始位置
    private Vector3[] originalObjectPositions;   // 所有子物体的原始位置
    private Coroutine moveCoroutine;             // 当前正在运行的协程
    private bool isAtOriginalPosition = true;    // 当前是否在原始位置

    private void Start()
    {
        // ✅ 记录初始位置
        if (imageRect != null)
            originalPos = imageRect.anchoredPosition;

        if (movingObjects != null && movingObjects.Length > 0)
        {
            originalObjectPositions = new Vector3[movingObjects.Length];
            for (int i = 0; i < movingObjects.Length; i++)
            {
                if (movingObjects[i] != null)
                    originalObjectPositions[i] = movingObjects[i].transform.localPosition;
            }
        }

        // ✅ 绑定按钮点击事件
        if (btn != null)
        {
            btn.onClick.AddListener(() =>
            {
                MoveImageAndObjects();
            });
        }
    }

    /// <summary>
    /// 主接口：触发图片和子物体一起移动或返回
    /// </summary>
    public void MoveImageAndObjects()
    {
        if (imageRect == null) return;

        Vector2 targetPos = GetTargetPosition(isAtOriginalPosition);

        if (moveCoroutine != null)
            StopCoroutine(moveCoroutine);

        moveCoroutine = StartCoroutine(SmoothMoveUIAndChildren(imageRect, targetPos, moveDuration));

        FlipButtonIcon(isAtOriginalPosition);

        isAtOriginalPosition = !isAtOriginalPosition;
    }

    /// <summary>
    /// 平滑移动图片及所有子物体到目标位置
    /// </summary>
    private IEnumerator SmoothMoveUIAndChildren(RectTransform rectTransform, Vector2 targetPosition, float duration)
    {
        Vector2 startPos = rectTransform.anchoredPosition;
        float elapsed = 0f;

        // 子物体起始/目标位置计算
        Vector3[] startObjectPos = null;
        Vector3[] endObjectPos = null;

        if (movingObjects != null && movingObjects.Length > 0)
        {
            startObjectPos = new Vector3[movingObjects.Length];
            endObjectPos = new Vector3[movingObjects.Length];

            Vector3 offset = (Vector3)(GetTargetPosition(true) - originalPos); // 计算偏移量

            for (int i = 0; i < movingObjects.Length; i++)
            {
                if (movingObjects[i] != null)
                {
                    startObjectPos[i] = movingObjects[i].transform.localPosition;
                    endObjectPos[i] = isAtOriginalPosition
                        ? originalObjectPositions[i] + offset
                        : originalObjectPositions[i];
                }
            }
        }

        // 平滑过渡过程
        while (elapsed < duration)
        {
            float t = elapsed / duration;

            rectTransform.anchoredPosition = Vector2.Lerp(startPos, targetPosition, t);

            if (movingObjects != null && movingObjects.Length > 0)
            {
                for (int i = 0; i < movingObjects.Length; i++)
                {
                    if (movingObjects[i] != null)
                        movingObjects[i].transform.localPosition = Vector3.Lerp(startObjectPos[i], endObjectPos[i], t);
                }
            }

            elapsed += Time.deltaTime;
            yield return null;
        }

        // 最终位置校准
        rectTransform.anchoredPosition = targetPosition;
        if (movingObjects != null && movingObjects.Length > 0)
        {
            for (int i = 0; i < movingObjects.Length; i++)
            {
                if (movingObjects[i] != null)
                    movingObjects[i].transform.localPosition = endObjectPos[i];
            }
        }
    }

    /// <summary>
    /// 将图片和所有对象重置为原始位置
    /// </summary>
    public void ResetPosition()
    {
        if (imageRect != null)
            imageRect.anchoredPosition = originalPos;

        if (movingObjects != null && originalObjectPositions != null)
        {
            for (int i = 0; i < movingObjects.Length; i++)
            {
                if (movingObjects[i] != null)
                    movingObjects[i].transform.localPosition = originalObjectPositions[i];
            }
        }

        FlipButtonIcon(false);
        isAtOriginalPosition = true;
    }

    /// <summary>
    /// 根据方向与状态，获取目标位置
    /// </summary>
    private Vector2 GetTargetPosition(bool toMovedPosition)
    {
        float distance = (currentDirection == Direction.Left || currentDirection == Direction.Right)
            ? imageRect.rect.width
            : imageRect.rect.height;

        Vector2 dir = currentDirection switch
        {
            Direction.Left => Vector2.left,
            Direction.Right => Vector2.right,
            Direction.Up => Vector2.up,
            Direction.Down => Vector2.down,
            _ => Vector2.zero
        };

        return toMovedPosition ? originalPos + dir * distance : originalPos;
    }

    /// <summary>
    /// 翻转按钮图标方向（左右翻转 X）
    /// </summary>
    private void FlipButtonIcon(bool isMoved)
    {
        Image icon = btn.transform.Find("Image")?.GetComponent<Image>();
        if (icon != null)
        {
            Vector3 scale = icon.rectTransform.localScale;
            scale.x = isMoved ? -1 : 1;
            icon.rectTransform.localScale = scale;
        }
    }
}
